import threading
from typing import Callable
import requests
import time
from datetime import datetime, timedelta
from loguru import logger
from functools import wraps
from SETTINGS import *

stats_lock = threading.Lock()


def monitor_sender(name, msg):
    """
    企微消息发送模块
    """
    headers = {
        'Content-Type': 'application/json',
    }
    content = f"👉任务: {name}\n👉报告时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n👉事件描述:{msg}"
    json_data = {
        'msgtype': 'text',
        'text': {
            'content': content,
            "mentioned_list": ["18826237037"],
        },
    }

    response = requests.post(
        MONITOR_URL,
        headers=headers,
        json=json_data
    )
    return response.status_code


def get_yesterday_timestamp():
    """
    获取昨天的时间戳,int
    """
    now = datetime.now()
    yesterday = now - timedelta(days=1)
    yesterday_zero_time = datetime(yesterday.year, yesterday.month, yesterday.day)
    yesterday_timestamp = int(time.mktime(yesterday_zero_time.timetuple()))
    return yesterday_timestamp


def api_stats_counter(func: Callable):
    @wraps(func)
    def wrapper(*args, **kwargs):
        global CALL_STATS
        with stats_lock:
            CALL_STATS[func.__name__]["total_calls"] += 1
        try:
            start_time = time.time()
            response = func(*args, **kwargs)
            with stats_lock:
                CALL_STATS[func.__name__]["successful_calls"] += 1
            end_time = time.time()
            execution_time = end_time - start_time
            logger.info(f"函数 {func.__name__} 的执行时间为 {execution_time} 秒")
            return response
        except Exception as e:
            with stats_lock:
                CALL_STATS[func.__name__]["failed_calls"] += 1
            raise e

    return wrapper


def get_stats():
    with stats_lock:
        return CALL_STATS
